﻿
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace AutomaticPush.Extension
{
    /// <summary>
    /// 小工具类型
    /// </summary>
    public class Tools
    {
        /// <summary>
        /// 获取分页
        /// </summary>
        /// <param name="_pageIndex">页码</param>
        /// <param name="_pageSize">每页多少条</param>
        /// <returns></returns>
        public static string GetLimit(int _pageIndex, int _pageSize)
        {
            int st = (_pageIndex - 1) * _pageSize;
            int ed = _pageSize;
            var pagesql = $" LIMIT {st},{ed} ";
            return pagesql;
        }

        /// <summary>
        /// 获取App.config中AppSetttings中的配置项
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public static string ReadAppSetting(string key)
        {
            string exeFileName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name + ".dll.config";
            ExeConfigurationFileMap map = new ExeConfigurationFileMap { ExeConfigFilename = exeFileName };
            var configuration = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            var strObj = configuration.AppSettings.Settings[key]; if (strObj == null)
            {
                throw new ArgumentException($"当前配置文件路径{configuration.FilePath}\n文件中appSettings节点下未配置名为：【{key}】的内容，请添加后再试");
            }
            return strObj.Value;
        }

        /// <summary>
        /// 修改App.config中AppSetttings中的配置项
        /// </summary>
        /// <param name="name">要修改的配置项的名称</param>
        /// <param name="value">要修改的配置项的值</param>
        /// <returns></returns>
        public static bool SetAppSettings(string name, string value, bool _ismodify = false)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);//当前应用程序的配置文件
                if (config != null)
                {
                    AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("appSettings");
                    if (appSettings.Settings.AllKeys.Contains(name))
                    {
                        if (_ismodify)
                            appSettings.Settings[name].Value = value;
                    }
                    else
                    {
                        appSettings.Settings.Add(name, value);
                    }
                    config.Save(); //保存配置文件
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("修改app.config配置{0}的值为{1}异常：{2}", name, value, ex.Message));
                return false;
            }
        }



        /// <summary>  
        /// 本地时间转成GMT时间  
        /// </summary>  
        public static string ToGMTString(DateTime dt)
        {
            return dt.ToUniversalTime().ToString("r");
        }
        public static string GetMd5FromString(string sInput)
        {
            var lstData = Encoding.GetEncoding("utf-8").GetBytes(sInput);
            var lstHash = new MD5CryptoServiceProvider().ComputeHash(lstData);
            var result = new StringBuilder(32);
            for (int i = 0; i < lstHash.Length; i++)
            {
                result.Append(lstHash[i].ToString("X2"));
            }
            return result.ToString();
        }




        /// <summary>
        /// 将字典转化为String字符串，并按照参数名ASCII码从小到大排序
        /// </summary>
        /// <param name="dataPara"></param>
        /// <returns></returns>
        public static string JoinToStrForm(Dictionary<string, string> dataPara)
        {
            var parameterAsc = dataPara.OrderBy(x => x.Key, new ComparerString()).ToDictionary(x => x.Key, y => y.Value);//参数按照参数名ASCII码从小到大排序
            List<string> list = new List<string>();
            foreach (var item in parameterAsc)
            {
                list.Add(item.Key + "=" + item.Value.Replace("#", "").Replace("?", "").Replace("&", "").Replace("=", ""));
            }

            return string.Join("&", list);
        }

        /// <summary>
        /// 比较对象字符串
        /// </summary>
        private class ComparerString : IComparer<string>
        {
            public int Compare(string x, string y)
            {
                return string.CompareOrdinal(x, y);
            }
        }



        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string md5(string data)
        {
            var lstData = Encoding.GetEncoding("utf-8").GetBytes(data);
            var lstHash = new MD5CryptoServiceProvider().ComputeHash(lstData);
            var result = new StringBuilder(32);
            for (int i = 0; i < lstHash.Length; i++)
            {
                result.Append(lstHash[i].ToString("x2"));
            }
            return result.ToString();
        }

        /// <summary>
        /// md5加密小写
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string md5ToLower(string data)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] bytValue, bytHash;
            bytValue = Encoding.UTF8.GetBytes(data);
            bytHash = md5.ComputeHash(bytValue);
            md5.Clear();
            string Temp = "";
            for (int i = 0; i < bytHash.Length; i++)
            {
                Temp += bytHash[i].ToString("X").PadLeft(2, '0');
            }
            return Temp.ToLower();
        }

        /// <summary>
        /// DateTime转时间戳
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public static long GetTimeStamp(DateTime dateTime)
        {
            // 开始时间
            DateTime startTime = new DateTime(1970, 1, 1, 8, 0, 0);
            // 10位的时间戳
            long timeStamp = Convert.ToInt64(dateTime.Subtract(startTime).TotalSeconds);
            // 13位的时间戳
            //long timeStamp = Convert.ToInt64(dateTime.Subtract(_dtStart).TotalMilliseconds);
            return timeStamp;
        }
        /// <summary>
        /// 时间戳
        /// </summary>
        /// <returns></returns>
        public static long GetDateTime()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
            //return Convert.ToInt64(ts.TotalMilliseconds);
        }
  
 

 
    }
}
